package com.aiyige.page.my.message.notifymessage.sysmessage.adapter;

import android.app.Activity;
import android.graphics.Path;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.UserCertification;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.authentication.model.Authentication;
import com.aiyige.page.my.message.notifymessage.sysmessage.model.Operation;
import com.aiyige.page.my.message.notifymessage.sysmessage.model.SystemMessage;
import com.aiyige.utils.DateFormatUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.LinkedList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.BindView;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * Created by zhuyakun on 2017/8/14.
 */

public class SystemMessageAdapter extends BaseQuickAdapter<SystemMessage, SystemMessageAdapter.ViewHolder> {
    CommonDataView commonDataView;

    public CommonDataView getCommonDataView() {
        return commonDataView;
    }

    public void setCommonDataView(CommonDataView commonDataView) {
        this.commonDataView = commonDataView;
    }

    public SystemMessageAdapter() {
        super(R.layout.system_message_item, new LinkedList<SystemMessage>());
    }

    @Override
    protected void convert(ViewHolder helper, SystemMessage data) {
        helper.bindData(data);
    }

    public class ViewHolder extends BaseViewHolder {
        @BindView(R.id.messageTitleTv)
        TextView messageTitleTv;
        @BindView(R.id.messageTimeTv)
        TextView messageTimeTv;
        @BindView(R.id.messageContentTv)
        TextView messageContentTv;
        @BindView(R.id.optionRv)
        RecyclerView optionRv;
        OperationAdapter operationAdapter;
        SystemMessage data;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            optionRv.setLayoutManager(new LinearLayoutManager(itemView.getContext(), LinearLayoutManager.HORIZONTAL, false));
            operationAdapter = new OperationAdapter();
            operationAdapter.bindToRecyclerView(optionRv);
            operationAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    switch (view.getId()) {
                        case R.id.viewAuthenticationBtn:
                            handleViewAuthentication();
                            break;
                        case R.id.reauthenticationBtn:
                            handleReauthentication();
                            break;
                        case R.id.agreeBtn:
                            handleAgree();
                            break;
                        case R.id.hasAgreedBtn:
                            handleHasAgreed();
                            break;
                        case R.id.ignoreBtn:
                            handleIgnore();
                            break;
                        case R.id.hasIgnoredBtn:
                            handleHasIgnored();
                            break;
                        case R.id.viewCouponBtn:
                            handleViewCoupon();
                            break;
                    }
                }
            });
        }

        public void bindData(SystemMessage data) {
            this.data = data;
            messageTitleTv.setText(data.getTitle());
            messageContentTv.setText(data.getContent());
            messageTimeTv.setText(DateFormatUtil.getStandardDate(data.getTime()));
            operationAdapter.setNewData(data.getOperationList());
        }

        public void handleAgree() {
            new AgreeTask((Activity) itemView.getContext(), getAdapterPosition()).execute();
        }

        public void handleIgnore() {
            new IgnoreTask((Activity) itemView.getContext(), getAdapterPosition()).execute();
        }

        public void handleViewAuthentication() {
            new ViewAuthenticationTask((Activity) itemView.getContext()).execute();
        }

        public void handleReauthentication() {
            new ReauthenticationTask((Activity) itemView.getContext()).execute();
        }

        public void handleHasAgreed() {

        }

        public void handleHasIgnored() {

        }

        public void handleViewCoupon() {
            ARouter.getInstance()
                    .build(ARouterConfig.UserCouponPage)
                    .navigation();
        }
    }

    public class AgreeTask extends SafeAsyncTask<Object, Object, Object> {
        int position;

        public AgreeTask(Activity activity, int position) {
            super(activity, R.string.text_process);
            this.position = position;
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof MessageHasBeenProcessedException) {
                ToastX.show((Exception) o);
                if (commonDataView != null) {
                    commonDataView.refresh();
                }
            } else if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                Operation operation = Operation.newBuilder()
                        .operationType(Operation.OPERATION_TYPE_AGREED_GUARANTEE)
                        .build();
                List<Operation> operationList = new LinkedList<>();
                operationList.add(operation);
                SystemMessage systemMessage = getItem(position);
                systemMessage.setOperationList(operationList);
                setData(position, systemMessage);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().agreeGuarantee(getItem(position).getId()).execute();
                if (response.code() != ResponseCode.CREATED) {
                    ErrorResponse errorResponse = ErrorUtil.handleErrorResponse(response);
                    if (errorResponse != null && ResponseCode.MESSAGE_HAS_BEEN_PROCESSED.equals(errorResponse.getCode())) {
                        throw new MessageHasBeenProcessedException(errorResponse.getMessage());
                    } else {
                        throw new Exception(errorResponse == null ? "" : errorResponse.getMessage());
                    }
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }


    }

    public static class MessageHasBeenProcessedException extends Exception {
        public MessageHasBeenProcessedException(String message) {
            super(message);
        }
    }

    public class IgnoreTask extends SafeAsyncTask<Object, Object, Object> {
        int position;

        public IgnoreTask(Activity activity, int position) {
            super(activity, R.string.text_process);
            this.position = position;
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof MessageHasBeenProcessedException) {
                ToastX.show((Exception) o);
                if (commonDataView != null) {
                    commonDataView.refresh();
                }
            } else if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                Operation option = Operation.newBuilder()
                        .operationType(Operation.OPERATION_TYPE_IGNORED_GUARANTEE)
                        .build();
                List<Operation> optionList = new LinkedList<>();
                optionList.add(option);
                SystemMessage systemMessage = getItem(position);
                systemMessage.setOperationList(optionList);
                setData(position, systemMessage);
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().ignoreGuarantee(getItem(position).getId()).execute();
                if (response.code() != ResponseCode.CREATED) {
                    ErrorResponse errorResponse = ErrorUtil.handleErrorResponse(response);
                    if (errorResponse != null && ResponseCode.MESSAGE_HAS_BEEN_PROCESSED.equals(errorResponse.getCode())) {
                        throw new MessageHasBeenProcessedException(errorResponse.getMessage());
                    } else {
                        throw new Exception(errorResponse == null ? "" : errorResponse.getMessage());
                    }
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }


    public class ViewAuthenticationTask extends SafeAsyncTask<Object, Object, Object> {
        Authentication authentication = null;

        public ViewAuthenticationTask(Activity activity) {
            super(activity, R.string.loading);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                switch (authentication.getUserType()) {
                    case Authentication.USER_TYPE_ORGANIZATION:
                        ARouter.getInstance()
                                .build(ARouterConfig.OrganizationAuthenticationPage)
                                .withParcelable("authentication", authentication)
                                .navigation();
                        break;
                    case Authentication.USER_TYPE_PERSONAL:
                        ARouter.getInstance()
                                .build(ARouterConfig.PersonalAuthenticationPage)
                                .withParcelable("authentication", authentication)
                                .navigation();
                        break;
                    default:
                        break;
                }
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getUserAuthenticationInfo().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                authentication = Authentication.parse(JSON.parseObject(json, UserCertification.class));
                return null;
            } catch (Exception e) {
                return e;
            }

        }
    }

    public class ReauthenticationTask extends SafeAsyncTask<Object, Object, Object> {
        Authentication authentication = null;

        public ReauthenticationTask(Activity activity) {
            super(activity, R.string.loading);
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                switch (authentication.getUserType()) {
                    case Authentication.USER_TYPE_ORGANIZATION:
                        ARouter.getInstance()
                                .build(ARouterConfig.OrganizationAuthenticationPage)
                                .withParcelable("authentication", Authentication.newBuilder()
                                        .userType(Authentication.USER_TYPE_ORGANIZATION)
                                        .readOnly(false)
                                        .build())
                                .navigation();
                        break;
                    case Authentication.USER_TYPE_PERSONAL:
                        ARouter.getInstance()
                                .build(ARouterConfig.PersonalAuthenticationPage)
                                .withParcelable("authentication", Authentication.newBuilder()
                                        .userType(Authentication.USER_TYPE_PERSONAL)
                                        .readOnly(false)
                                        .build())
                                .navigation();
                        break;
                    default:
                        break;
                }
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().getUserAuthenticationInfo().execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                String json = RetrofitUtil.getResponseBodyAsString(response);
                authentication = Authentication.parse(JSON.parseObject(json, UserCertification.class));
                return null;
            } catch (Exception e) {
                return e;
            }

        }
    }
}
